package club.jdiy.admin.freemarker.func;

import club.jdiy.core.AdminContext;
import club.jdiy.core.base.domain.DictInfo;
import club.jdiy.utils.StringUtils;
import freemarker.template.SimpleScalar;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class GetDictInfo implements TemplateMethodModelEx {
    public Object exec(List argList) throws TemplateModelException {
        if (argList.size() < 2) {
            throw new TemplateModelException("错误的参数。");
        }
        String p1 = ((SimpleScalar) argList.get(0)).getAsString();
        Object p2Obj = argList.get(1);
        if (p2Obj == null) return "";
        String p2 = ((SimpleScalar) p2Obj).getAsString();

        DictInfo dictInfo = adminContext.getDict(p1, p2).orElse(null);
        if (dictInfo == null) return p2;
        return withColor(dictInfo);
    }

    public static String withColor(DictInfo dictInfo){
        return StringUtils.hasText(dictInfo.getColor())
                ? "<span class=\"dictInfo\" style=\"color:" + dictInfo.getColor() + ";\">" + dictInfo.getName() + "</span>"
                : dictInfo.getName();
    }

    @Resource
    private AdminContext adminContext;
}